package cn.sytton.taffe.web.sys.service.impl;

import cn.sytton.taffe.framework.exception.BizException;
import cn.sytton.taffe.framework.util.SecurityUtil;
import cn.sytton.taffe.web.sys.entity.UserEntity;
import cn.sytton.taffe.web.sys.service.IUserService;
import cn.sytton.taffe.framework.base.service.BaseService;
import cn.sytton.taffe.framework.util.PwdUtil;
import cn.sytton.taffe.web.sys.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 用户服务层
 *
 * @author skyrock
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class UserService extends BaseService<UserMapper, UserEntity> implements IUserService {

    @Override
    public void create(UserEntity entity) {
        entity.setPassword(PwdUtil.encode(entity.getPassword()));
        super.create(entity);
    }

    @Override
    public void createOrUpdate(UserEntity entity) {
        if (!StringUtils.checkValNull(entity.getUserId()) && !Objects.isNull(this.getById(entity.getUserId()))) {
            super.updateById(entity);
        } else {
            create(entity);
        }
    }

    @Override
    public void updatePwd(UserEntity entity) {
        updateWithUpdateField(new LambdaUpdateWrapper<UserEntity>()
                .set(UserEntity::getPassword, PwdUtil.encode(entity.getPassword()))
                .eq(UserEntity::getUserId, entity.getUserId()));
    }

    @Override
    public void updateUserStatus(UserEntity entity) {
        updateWithUpdateField(new LambdaUpdateWrapper<UserEntity>()
                .set(UserEntity::getUserStatus, entity.getUserStatus())
                .eq(UserEntity::getUserId, entity.getUserId()));
    }

    @Override
    public void updateMyPwd(String oldPwd, String newPwd) {
        UserEntity user = findById(SecurityUtil.getUserId());
        if (user != null) {
            if (PwdUtil.matches(oldPwd, user.getPassword())) {
                user.setPassword(newPwd);
                updatePwd(user);
            } else {
                throw new BizException("旧密码错误");
            }
        } else {
            throw new BizException ("用户不存在");
        }
    }

    @Override
    public List<UserEntity> findByIds(String[] ids) {
        return super.listByIds(Arrays.asList(ids));
    }
}
